package com.rmb.thread;

import java.util.concurrent.*;

/**
 * @author wan
 * @Title: ThreadManager
 * @Package util
 * @Description: wan
 * @date 2021/1/128:57
 */
public class ThreadManager {

    private static ThreadPoolProxy threadPoolProxy;

    public static ThreadPoolProxy getThreadPoolProxy(){
        synchronized (ThreadPoolProxy.class){
            if(threadPoolProxy == null){
                threadPoolProxy = new ThreadPoolProxy(10, 40, 10);
            }
        }
        return threadPoolProxy;
    }

    public static class ThreadPoolProxy{
        private ThreadPoolExecutor poolExecutor;//线程执行者
        private int corePoolSize;//核心线程数
        private int maximumPoolSize;//最大线程数
        private long keepAliveTime;//线程存活时间

        public ThreadPoolProxy(int corePoolSize,int maximumPoolSize,long keepAliveTime){
            this.corePoolSize = corePoolSize;
            this.maximumPoolSize = maximumPoolSize;
            this.keepAliveTime = keepAliveTime;
        }

        public void execute(Runnable runnable){
            if(poolExecutor==null || poolExecutor.isShutdown()){
                ThreadFactory threadFactory = Executors.defaultThreadFactory();
                poolExecutor = new ThreadPoolExecutor(
                        corePoolSize,
                        maximumPoolSize,
                        keepAliveTime,
                        TimeUnit.SECONDS,
                        new ArrayBlockingQueue<>(30), threadFactory);
            }
            poolExecutor.execute(runnable);
            System.out.println("核心线程数" + poolExecutor.getCorePoolSize());
            System.out.println("最大线程数" + poolExecutor.getMaximumPoolSize());
            System.out.println("线程池数" + poolExecutor.getPoolSize());
            System.out.println("队列任务数" + poolExecutor.getQueue().size());
            System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
            poolExecutor.shutdown();
        }
    }
}
